import { setToken, getToken, removeToken } from '@/utils/auth'
import { login } from '@/api/user'
const state = {
  // 读取本地存储
  userInfo: localStorage.getItem('userInfo') || {},
  token: getToken() || null
}

const mutations = {
  setToken(state, newToken) {
    // 保存token到vuex
    state.token = newToken
    // 保存到cookie
    setToken(newToken)
  },

  setUserInfo(state, newInfo) {
    state.userInfo = newInfo

    // 存储到本地
    localStorage.setItem('userInfo', JSON.stringify(newInfo))
  },
  // 删除
  logout(state) {
    state.token = ''
    state.userInfo = {}

    // 清空本地存储
    localStorage.clear('userInfo')

    // 清空cookie
    removeToken()
  }

}

const actions = {
  // async getProfile(context) {
  //   const result = await getProfile()
  //   console.log(result)
  //   const userInfo = { name: '测试' }
  //   context.commit('setUserInfo', userInfo)
  // },

  async login(context, payload) {
    // console.log(context, payload)
    // 登录请求
    const result = await login(payload)
    console.log(result)
    const token = result.data.token.token
    // 处理token
    context.commit('setToken', token)
    // 处理用户信息
    context.commit('setUserInfo', result.data.user)
  },
  // 退出功能
  logout(context) {
    context.commit('logout')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

